const logger = require('log4js').getLogger()
const Wechat = require('../util/Wechat')

module.exports = (req, res) => {
    require('../util/service').handlePost(req, res, (reqObj, resolve) => {
        const mongoMng = require('../mng/mongoMng')
        if (!mongoMng.db) {
            logger.error('[' + __filename + ':' + __line + ']', '未连接mongo')
            resolve({
                result: -1,
                msg: '系统错误'
            })
            return;
        }
        if (!reqObj.phone) {
            resolve({
                result: -1,
                msg: '缺少phone'
            })
            return
        }
        if (reqObj.code) {
            var date = new Date()
            date.setTime(date.getTime() - 1800000)
            mongoMng.db.collection('code').find({
                phone: reqObj.phone,
                code: reqObj.code,
                time: {
                    $gte: require('../../lib/formatDate')(date)
                }
            }).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve({
                        result: -1,
                        msg: '系统错误'
                    })
                    return
                }
                if (result.length == 0) {
                    resolve({
                        result: -1,
                        msg: '手机号或验证码错误'
                    })
                    return
                }
                mongoMng.db.collection('user').find({
                    phone: reqObj.phone
                }).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        resolve({
                            result: -1,
                            msg: '系统错误'
                        })
                        return;
                    }
                    if (result.length == 0) {
                        resolve({
                            result: -1,
                            msg: '该手机号未注册'
                        })
                        return
                    }
                    require('../util/loginResolve')(result[0], req, resolve)
                    if (reqObj.password || req.session.wechat) {
                        var set = {}
                        if (reqObj.password)
                            set.password = reqObj.password
                        if (req.session.wechat) {
                            logger.debug('[' + __filename + ':' + __line + ']', 'phone:', result[0].phone, 'old whchat:', result[0].wechat, 'new wehcat:', req.session.wechat.openid)
                            set.wechat = req.session.wechat.openid
                        }
                        mongoMng.db.collection('user').update({
                            phone: result[0].phone
                        }, {
                            $set: set
                        }, (err, result) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                return
                            }
                            if (req.session.wechat) {
                                Wechat({
                                    AppID: 'wx226c3c9557c44304',
                                    AppSecret: '8bff6155d050947d06bf7802e69f4acb'
                                }).messageCustomSend({
                                    touser: req.session.wechat,
                                    msgtype: 'text',
                                    content: '绑定成功'
                                }).then(result => {
                                    logger.debug('[' + __filename + ':' + __line + ']', result)
                                }, result => {
                                    logger.error('[' + __filename + ':' + __line + ']', result)
                                })
                            }
                        })
                    }
                })
            })
        } else if (reqObj.password) {
            mongoMng.db.collection('user').find({
                phone: reqObj.phone,
                password: reqObj.password
            }).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve({
                        result: -1,
                        msg: '系统错误'
                    })
                    return;
                }
                if (result.length == 0) {
                    resolve({
                        result: -1,
                        msg: '手机号或密码错误'
                    })
                    return
                }
                require('../util/loginResolve')(result[0], req, resolve)
                if (req.session.wechat) {
					if (req.session.wechat.openid != result[0].wechat) {
						logger.debug('[' + __filename + ':' + __line + ']', 'phone:', result[0].phone, 'old whchat:', result[0].wechat, 'new wehcat:', req.session.wechat.openid)
						mongoMng.db.collection('user').update({
							phone: reqObj.phone
						}, {
							$set: {
								wechat: req.session.wechat.openid
							}
						}, (err, result) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                return
                            }
                            if (req.session.wechat) {
                                Wechat({
                                    AppID: 'wx226c3c9557c44304',
                                    AppSecret: '8bff6155d050947d06bf7802e69f4acb'
                                }).messageCustomSend({
                                    touser: req.session.wechat,
                                    msgtype: 'text',
                                    content: '绑定成功'
                                }).then(result => {
                                    logger.debug('[' + __filename + ':' + __line + ']', result)
                                }, result => {
                                    logger.error('[' + __filename + ':' + __line + ']', result)
                                })
                            }
                        })
					}
                }
            });
        } else {
            resolve({
                result: -1,
                msg: '缺少password或code'
            })
            return
        }
    })
}